import Vue from 'vue'
import Router from './router'
import plugins from '@/plugins'
import store from './store'
import '@/styles/index.scss'
import api from '@/api'

// 注册插件
plugins(Vue)
// 注册api
registerApi(api)

/* 在vue原型上全局注册api接口 */
export function registerApi(apis = {}) {
  // 递归更新api
  const mergeObject = (newObj = {}, oldObj = {}) => {
    const result = {}
    Object.keys(oldObj).forEach((key) => {
      result[key] = oldObj[key]
    })
    Object.keys(newObj).forEach((key) => {
      if (typeof oldObj[key] === 'object') {
        result[key] = mergeObject(newObj[key], oldObj[key])
      } else {
        result[key] = newObj[key]
      }
    })
    return result
  }
  Vue.prototype.$api = mergeObject(apis, Vue.prototype.$api)
}

/* 注册页面 */
export function registerProject(options = {}) {
  console.log('options', options)
  // 动态注册vuex模块
  if (typeof options.store !== 'undefined') {
    Object.keys(options.store).forEach(key => {
      store.registerModule(key, options.store[key])
    })
  }

  Router.setOption(options.router)

  // 返回一个Vue实例，在子项目中挂载到app上($mount('#app'))
  return new Vue({
    router: Router.getInstance(),
    store,
    render: options.render
  })
}

/* 导出vue供外部自定义使用 */
export default Vue
